<%@ page language="java" contentType="text/html; charset=UTF-8" import="java.util.*,
com.brother.model.*,com.brother.service.*,com.brother.realtime.*,com.brother.realtime.config.*"   pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ include file="../international.jsp" %> 
<%
String trackerId = request.getParameter("trackerId");
TrackerService tks = new TrackerService();

Tracker tracker = tks.getTrackerByFieldName("trackerId", trackerId);

AlarmService alService = new AlarmService();
Alarm overSpeedAlarm = new Alarm();
overSpeedAlarm.setTrackerId(trackerId);
overSpeedAlarm.setAlarmType(AlarmType.Over_Speed_Alarm.toString());
List<Alarm> alarms = alService.findAlarms(overSpeedAlarm);
overSpeedAlarm = alarms.size() > 0 ? alarms.get(0):null;

Alarm timezoneAlarm = new Alarm();
timezoneAlarm.setTrackerId(trackerId);
timezoneAlarm.setAlarmType(AlarmType.Set_Time_Zone.toString());
alarms = alService.findAlarms(timezoneAlarm);
timezoneAlarm = alarms.size() > 0 ? alarms.get(0):null;


%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title><fmt:message key="tracker.parameters.set"/></title>
<link rel="stylesheet" type="text/css" media="all" href="../style.css"/>
<link rel="stylesheet" type="text/css" href="../css/ext-all.css" />
<link rel="stylesheet" type="text/css" href="../css/examples.css" />
    <script type="text/javascript" src="../js/ext-base.js"></script>
    <script type="text/javascript" src="../js/ext-all.js"></script>
<script type="text/javascript" src="../js/extexample.js"></script>
<script type="text/javascript" src="../js/TableGrid.js"></script>
<script type="text/javascript" src="../js/common.js"></script>

<script type="text/javascript">

var ime = '<%=tracker.getUserTrackerId()%>';
var waitingMsg = '<fmt:message key="waiting.msg"/>';
var waitingProgressText = '<fmt:message key="waiting.loading"/>';

var trackerId = '<%=trackerId%>';
var setupmsg = '<fmt:message key="parameters.setup.msg"/>';
var setupProgresstext = '<fmt:message key="parameters.setup.progress"/>';

Number.prototype.GpsFormat = function(format){
	if(typeof format == 'undefined' || format == null){
		return this.Value;
	}
	format = format.toString();
	var result = this.toString();
	
	if(format.match(/^[0]+$/)){
		var s = result.toString();
		s = format + s; 
		result = s.substring(s.length - format.length, s.length);
		
	}
	
	return result;
};

function apply(work, action,data){
	if(work == 'disable'){
		return;
	}
	setInfo();
	Ext.Ajax.request({
		method:'POST',
		url: './setControl.jsp',
	    params: {action:action,data:data,work:work, trackerId:trackerId},
	    success:function(){
			if(action == 'reqStatus')
				queryAllStatus();
			else
			querySetStatus(action);
	    }
	});
	
}

function setInfo(){
    Ext.MessageBox.show({
        msg: setupmsg,
        progressText: setupProgresstext,
        width:300,
        //wait:true,
        //waitConfig: {interval:200},
        progress:true,
        closable:false
        //icon:'ext-mb-download'
    });
}

var setSuccess = "<fmt:message key="parameters.set.success"/>";
var setFailed = "<fmt:message key="parameters.set.failed"/>";

var failedCount = 15;

function formatTimeInterval(num){
	num = parseInt(num)*10;
	if(num < 10){
		return '00'+num+'S';
	}else if(num < 100){
		return '0'+num+'S';
	}else if(num < 255){
		return ''+num;
	}else if(num > 255 && num <= 255*60){ // 超过255秒，用分钟
		var m = Math.floor(num / 60);
		m = new Number(m);
		return m.GpsFormat('000')+'M';
	}else if(num > 255*60){ // 超过255分钟，用分钟
		var m = Math.floor(num / 60 / 60);
		return m.GpsFormat('000')+'H';
	}
	return num+'';
}

// 测试时间间隔
function checkNumber(num){
	if(!num.match(/^\d+$/)){
		Ext.MessageBox.show({
            title: '',
            msg: '<fmt:message key="parameters.number.format.error"/>',
            buttons: Ext.MessageBox.OK,
            icon: Ext.MessageBox.ERROR
        });
		return false;
	}
	return true;
}

function checkNumberAuthNumSel(){
	var type = setAuthNumberBox.getValue();
	if(type.indexOf(":") != 0){ 
		Ext.MessageBox.show({
            title: '',
            msg: '<fmt:message key="parameters.set.auth.select"/>',
            buttons: Ext.MessageBox.OK,
            icon: Ext.MessageBox.ERROR
        });
		return false;
	}
	return true;
}
function checkNumberAuthNum(num){
	var type = setAuthNumberBox.getValue();
	if(type.indexOf(":") != 0){ 
		Ext.MessageBox.show({
            title: '',
            msg: '<fmt:message key="parameters.set.auth.select"/>',
            buttons: Ext.MessageBox.OK,
            icon: Ext.MessageBox.ERROR
        });
		return false;
	}
	if(num == "" ||	(!num.substring(1).match(/^\d+$/))){
		Ext.MessageBox.show({
            title: '',
            msg: '<fmt:message key="parameters.number.format.error"/>',
            buttons: Ext.MessageBox.OK,
            icon: Ext.MessageBox.ERROR
        });
		return false;
	}
	return true;
}



// 设置速度限制
function checkNumber2(m){
	if(!m.match(/^\d+$/)){
		Ext.MessageBox.show({
            title: '',
            msg: '<fmt:message key="parameters.number.format.error"/>',
            buttons: Ext.MessageBox.OK,
            icon: Ext.MessageBox.ERROR
        });
		return false;
	}

	var num = new Number(m);
	if(num > 250){
		Ext.MessageBox.show({
            title: '',
            msg: '<fmt:message key="parameters.number.exceed"/>',
            buttons: Ext.MessageBox.OK,
            icon: Ext.MessageBox.ERROR
        });
		return false;
	}

	
	return true;
}

//  判断电量报警线
function checkNumber3(num){
	if(!num.match(/^\d+$/)){
		Ext.MessageBox.show({
            title: '',
            msg: '<fmt:message key="parameters.number.format.error"/>',
            buttons: Ext.MessageBox.OK,
            icon: Ext.MessageBox.ERROR
        });
		return false;
	}
	num = new Number(num);
	if(num > 45){
		Ext.MessageBox.show({
            title: '',
            msg: '<fmt:message key="parameters.number.exceed.45"/>',
            buttons: Ext.MessageBox.OK,
            icon: Ext.MessageBox.ERROR
        });
		return false;
	}

	return true;
}

function checkPass(p){
	if(!p.match(/^\d+$/)){
		Ext.MessageBox.show({
            title: '',
            msg: '<fmt:message key="parameters.password.6"/>',
            buttons: Ext.MessageBox.OK,
            icon: Ext.MessageBox.ERROR
        });
		return false;
	}
	if(p.length != 6){
		Ext.MessageBox.show({
            title: '',
            msg: '<fmt:message key="parameters.password.6"/>',
            buttons: Ext.MessageBox.OK,
            icon: Ext.MessageBox.ERROR
        });
		return false;
	}
	
	return true;
}

//设置速度限制
function formatSpeed(m){
	var num = new Number(m);
	return num.GpsFormat('000');
}

function querySetStatus(action){
	var count = 0;

	function fun(){
		count +=1;

		Ext.Ajax.request({
			url:'queryStatus.jsp',
		    form: 'control',
		    params: 'action='+action,
		    success:function(res){
				var text = res.responseText;
				if(text.indexOf("1") > -1 || text.indexOf('true') > -1){
					Ext.MessageBox.hide();
					Ext.example.msg('<div class="right"></div>', '<div><br/>'+setSuccess+'<div>');
					
					count = failedCount;
					return;
				}else if(count == failedCount){
					Ext.MessageBox.hide();
					//alert(setFailed);
					Ext.MessageBox.show({
        	            title: '',
        	            msg: setFailed,
        	            buttons: Ext.MessageBox.OK,
        	            icon: Ext.MessageBox.ERROR
        	        });
				}else if(text == 'error'){
					Ext.MessageBox.hide();
					//alert(setFailed);
					Ext.MessageBox.show({
        	            title: '',
        	            msg: setFailed,
        	            buttons: Ext.MessageBox.OK,
        	            icon: Ext.MessageBox.ERROR
        	        });
					return;
				}
				if(count < failedCount){
					window.setTimeout(fun, 1000);
					var percent = count / failedCount;
					Ext.MessageBox.updateProgress(percent, Math.round(100*percent)+'%');
				}
		    }
		});
	}
	fun();
}


function queryAllStatus(){
	var count = 0;
	
	function fun2(){
		count +=1;

		Ext.Ajax.request({
			url:'queryStatus.jsp',
		    form: 'control',
		    params: 'action=reqStatus',
		    success:function(res){
				var text = res.responseText;
				
				if(text.length > 2){
					var datas = text.split(",");
					Ext.MessageBox.hide();
					if(datas.length == 9){
						Ext.example.msg('<div class="right"></div>', '<div><br/>'+setSuccess+'<div>');
						count = failedCount;
						document.getElementById("intervalText").innerHTML = datas[0];
						document.getElementById("speedText").innerHTML = datas[1];
						document.getElementById("numberaText").innerHTML = datas[2];
						document.getElementById("numberbText").innerHTML = datas[3];
						document.getElementById("numbercText").innerHTML = datas[4];
						document.getElementById("timezoneText").innerHTML = datas[5];

						document.getElementById("engineText").innerHTML = datas[6];
						document.getElementById("coordinateText").innerHTML = datas[7];
						document.getElementById("powerText").innerHTML = datas[8];
					}else{ //alert(setFailed);
						Ext.MessageBox.show({
	        	            title: '',
	        	            msg: setFailed,
	        	            buttons: Ext.MessageBox.OK,
	        	            icon: Ext.MessageBox.ERROR
	        	        });
					}
					
					return;
				}else if(count == failedCount){
			         Ext.MessageBox.hide();
			        // Ext.example.msg('Done', 'Your fake data was saved!');
			        Ext.MessageBox.show({
	        	            title: '',
	        	            msg: setFailed,
	        	            buttons: Ext.MessageBox.OK,
	        	            icon: Ext.MessageBox.ERROR
	        	        });
					//alert(setFailed);
				}
				if(count < failedCount){
					window.setTimeout(fun2, 1000);
					var percent = count / failedCount;
					Ext.MessageBox.updateProgress(percent, Math.round(100*percent)+'%');
				}
		    }
		});
		
		
	}
	
	
	fun2();
}

var setAuthNumberBox = null;
Ext.onReady(function(){

	//history.length = 0;
	Ext.MessageBox.buttonText.yes = '<fmt:message key="button.yes.text"/>';
	Ext.MessageBox.buttonText.no = '<fmt:message key="button.no.text"/>';
	Ext.MessageBox.buttonText.cancel = '<fmt:message key="button.cancel.text"/>';
	var buttons = Ext.select('input[type="button"]');
	buttons.each(function(item,c, index){
		//item.setStyle('display','none');
	});
    // create the grid
    Ext.get("plain-table").setStyle('display','');

    function createSelection(){
    	Ext.get("setAuthNumber").setStyle('display','');  
        // simple array store
        var store = new Ext.data.ArrayStore({
            fields: ['numType', 'code', 'ff'],
            data : [['<fmt:message key="parameters.set.number.a1"/>',':123456A1',''],['<fmt:message key="parameters.set.number.a2"/>',':123456A2',''],['<fmt:message key="parameters.set.number.a3"/>',':123456A3',''],['<fmt:message key="parameters.set.number.a4"/>',':123456A4',''],['<fmt:message key="parameters.set.number.a5"/>',':123456A5','']]
        });
        /*
        if('<%=tracker.getCarmodelId()%>' == '9'){ // TL108
        	store = new Ext.data.ArrayStore({
                fields: ['numType', 'code', 'ff'],
                data : [['SOS',':123456A1',''],['SOS',':123456A2',''],['SOS',':123456A3',''],['Call Center',':123456A4',''],['Call 2',':123456A5','']]
            });
         }*/
        
        setAuthNumberBox = new Ext.form.ComboBox({
            store: store,
            displayField:'numType',
            valueField:'code',
            typeAhead: true,
            editable:false,
            mode: 'local',
            forceSelection: false,
            triggerAction: 'all',
            emptyText:'<fmt:message key="parameters.set.authorized.numbers"/>',
            selectOnFocus:true,
            applyTo: 'setAuthNumber'});
        }
    
    var grid = new Ext.ux.grid.TableGrid("plain-table", {
        stripeRows: true, // stripe alternate rows
        enableHdMenu:false,
        width:688,
        disableSelection:false,
        listeners:{afterrender:function(){window.setTimeout(createSelection,1000)}}});
    grid.render();

function createButton(){
	return;
    var buttons = grid.getEl().select('input[type="button"]');
    if(buttons.getCount() == 0){
		setTimeout(createButton, 500);
		return;
    }
    //console.log(buttons, 1000, grid.getEl().dom);
    buttons.each(function(item,c, index){
		
        var button = new Ext.Button({renderTo:item.parent(),type:'button', 
			text:item.getAttribute('value'),split: true,enableToggle:false});
		button.on('click',function(){
			try{ eval(item.getAttribute('onclick')); }catch(e){}
			});
        item.remove();
    });
}

//createButton();




});

function checkTimeZone(){
//  document.getElementById('timezone').value.length < 3
	var value = document.getElementById('timezone3').value;
	if(!value.match(/^[\+-]\d{1}\.{1}\d{1}$/)
			&& !value.match(/^[\+-]\d{2}$/)){
		Ext.MessageBox.show({
            title: '',
            msg: '<fmt:message key="parameters.timezone.format.error"/>',
            buttons: Ext.MessageBox.OK,
            icon: Ext.MessageBox.ERROR
        });
        return false;
	}
	return true;
}

// 在号码之前添加+号
function addPlus(textBox){
	var v = textBox.value;
	if(v != '' && v.indexOf("+") != 0){
		textBox.value = "+"+v;
	}
}
</script>

<style type="text/css">

body{
	background-color:#FFFFFF;
}

.x-grid3-cell-inner  {
text-align:left;
white-space:nowrap;
}

.x-btn{
float: left;
padding-left:3px;
}


</style>

</head><body>
<div style="text-align: center">
<form id="control" name="control" method="post" action="./setControl.jsp">
<input name="trackerId" value="<%=tracker.getTrackerid()%>" type="hidden">

<table align="center" border="1" style="display:none;" id="plain-table"  cellpadding="2" cellspacing="1">
  <tbody>
  <thead>
  <tr>
    <th width="200"><fmt:message key="parameters.operation"/>:</th>
    <th width="300"><fmt:message key="parameters.parameter.value"/>:</th>
    <th width="250"><fmt:message key="parameters.function.switch"/></th>
  </tr>
  </thead>
  
   <tr>
    <td align="left"><div><input type="text" style="display:none" id="setAuthNumber" size="25"/></div></td>
    <td align="left"><input name="authNum" onkeyup="addPlus(this)" type="text" onclick="this.focus()"  id=authNum value="" size="20"/></td>
    <td align="left"><a href="#noaction" onclick="if(checkNumberAuthNum(document.getElementById('authNum').value)) apply('enable', 'authNum', setAuthNumberBox.getValue()+','+document.getElementById('authNum').value+'#');"><fmt:message key="parameters.enable"/></a>
    <a href="#noaction" onclick="if(checkNumberAuthNumSel()) apply('enable', 'authNum', setAuthNumberBox.getValue()+',D#');"><fmt:message key="parameters.disable"/></a></td>
  </tr>

  
   <tr>
    <td align="left"><fmt:message key="parameters.locate.one.time"/></td>
    <td align="left">&nbsp;</td>
    <td align="left"><a href="#noaction" onclick="apply('enable', 'locate')"><fmt:message key="parameters.enable"/></a></td>
  </tr>
  
   <tr>
    <td align="left"><fmt:message key="parameters.set.time.interval"/></td>
    <td align="left">
    <input name="conTrack" type="text" onclick="this.focus()"  id="conTrack" value="" size="20"/>(<fmt:message key="control.report.interval.unit"/>)</td>
    <td align="left"><a href="#noaction" onclick="if(checkNumber(document.getElementById('conTrack').value)) apply('enable', 'conTrack', ':123456M1,'+formatTimeInterval(document.getElementById('conTrack').value)+'#');"><fmt:message key="parameters.enable"/></a>
    <a href="#noaction" onclick="if(checkNumber(document.getElementById('conTrack').value)) apply('enable', 'conTrack', ':123456M0,'+formatTimeInterval(document.getElementById('conTrack').value)+'#');"><fmt:message key="parameters.disable"/></a></td>
  </tr>
  
  <tr>
    <td align="left"><fmt:message key="parameters.over.speed.alarm"/></td>
    <td align="left">
    <input name="speed3" type="text" onclick="this.focus()"  id="speed3" value="<%=overSpeedAlarm == null ? "":overSpeedAlarm.getValue1() %>" size="20"/> KM/H</td>
    <td align="left"><a href="#noaction" onclick="if(checkNumber2(document.getElementById('speed3').value)) apply('enable', 'speed3', ':123456J1,'+formatSpeed(document.getElementById('speed3').value)+'#');"><fmt:message key="parameters.enable"/></a>
    <a href="#noaction" onclick="if(checkNumber2(document.getElementById('speed3').value)) apply('enable', 'speed3', ':123456J0,'+formatSpeed(document.getElementById('speed3').value)+'#');"><fmt:message key="parameters.disable"/></a></td>
  </tr>
  
  <tr>
    <td><fmt:message key="parameters.modify.time.zone"/></td>
    <td><input name="timezone3" type="text" onclick="this.focus()"  id="timezone3" value="<%=timezoneAlarm == null ? "":timezoneAlarm.getData() %>" size="20"/>&nbsp;</td>
    <td><a href="#noaction" onclick="if(!checkTimeZone()){  return; }; apply('enable', 'timezone3', ':123456L'+document.getElementById('timezone3').value+'#');"><fmt:message key="parameters.enable"/></a>
    
      </td>
  </tr>
  
  <tr>
    <td><fmt:message key="parameters.low.battery.alarm"/></td>
    <td><input name="lowBatAlarm" type="text" onclick="this.focus()"  id="lowBatAlarm" value="<%=timezoneAlarm == null ? "":timezoneAlarm.getData() %>" size="20"/>&nbsp;%</td>
    <td><a href="#noaction" onclick="if(checkNumber3(document.getElementById('lowBatAlarm').value)) apply('enable', 'lowBatAlarm',':123456N1,'+document.getElementById('lowBatAlarm').value+'#');"><fmt:message key="parameters.enable"/></a>
    <a href="#noaction" onclick="if(checkNumber3(document.getElementById('lowBatAlarm').value)) apply('enable', 'lowBatAlarm',':123456N0,'+document.getElementById('lowBatAlarm').value+'#');"><fmt:message key="parameters.disable"/></a>
      </td>
  </tr>
  
  <tr>
    <td><fmt:message key="parameters.engine.control"/></td>
    <td>&nbsp;</td>
    <td><a href="#noaction" onclick="apply('enable', 'cutAcc');"><fmt:message key="parameters.engine.stop"/></a>
    <a href="#noaction" onclick="apply('enable', 'recoverAcc');"><fmt:message key="parameters.engine.disable"/></a>
      </td>
  </tr>
  
  <tr>
    <td><fmt:message key="parameters.switch.listen.mode"/></td>
    <td>&nbsp;</td>
    <td><a href="#noaction" onclick="apply('enable', 'toListen');"><fmt:message key="parameters.enable"/></a>
      </td>
  </tr>
  
  <tr>
    <td><fmt:message key="parameters.switch.talk.mode"/></td>
    <td>&nbsp;</td>
    <td><a href="#noaction" onclick="apply('enable', 'toTalk');"><fmt:message key="parameters.enable"/></a>
      </td>
  </tr>
  
</tbody>
</table>
</form>

</div>

</body></html>
<%
com.brother.database.DataBase.closeThreadConnection();
%>